﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ToolGab.Classes;
using ToolGab.Cleaner.Forms;
using System.Collections.Generic;

namespace ToolGab.Cleaner
{
  
    ///============================================================================================
    /// <summary>
    /// Main Form
    /// </summary>
    ///============================================================================================
    public partial class MainForm : Form
    {
        List<DirectoryInfo> m_chkDI;

        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Store the dateTime starting time, to be able to calculate the time elapsed
        /// </summary>
        ///----------------------------------------------------------------------------------------
        private DateTime m_Start;
        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Files deleted count
        /// </summary>
        ///----------------------------------------------------------------------------------------
        private long m_FilesDeleted = 0;

        public MainForm()
        {
            Splasher.Status = "Creating the main form...";
            InitializeComponent();
            this.mainMenuFileExit.Image = ToolGab.Ressources.GetImage("ApplicationExit");
            this.mainMenuCleanerStart.Image = ToolGab.Ressources.GetImage("CleanerStart");
            this.mainMenuCleanerShortcuts.Image = ToolGab.Ressources.GetImage("application_shortcut");
            this.mainMenuShowResults.Image = ToolGab.Ressources.GetImage("application_split");
            this.mainMenuHelpAbout.Image = ToolGab.Ressources.GetImage("AboutIcon");
            this.tsMainExit.Image = this.mainMenuFileExit.Image;
            this.tsMainAbout.Image = this.mainMenuHelpAbout.Image;
            this.tsMainStart.Image = this.mainMenuCleanerStart.Image;
            this.tsMainShortcut.Image = this.mainMenuCleanerShortcuts.Image;
            this.tsMainResultView.Image = this.mainMenuShowResults.Image;

            m_chkDI = new List<DirectoryInfo>();

            chDeletedFiles.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);

            // Load the drive in the Treeview
            Splasher.Status = "Loading system drive...";
            LoadDriveInTreeView();

            // Load the extensions into the lvwExt
            Splasher.Status = "Loading Extensions (Default and customs)...";
            LoadExtensions();

            // Close the splash screen
            Splasher.Status = "Close Splash screen...";

            Splasher.Close();

        }

        #region Menus

        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Open the About dialog form.
        /// </summary>
        ///----------------------------------------------------------------------------------------
        private void mainMenuHelpAbout_Click(object sender, EventArgs e)
        {
            AboutForm frmAbout = new AboutForm();

            frmAbout.ShowDialog(this);
        }

        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Quit the application.
        /// </summary>
        ///----------------------------------------------------------------------------------------

        private void mainMenuFileExit_Click(object sender, EventArgs e)
        {
            ApplicationExit();
        }
        #endregion

        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// End properly the application
        /// </summary>
        ///----------------------------------------------------------------------------------------
        private void ApplicationExit()
        {
            // Save the default settings
            Properties.Settings.Default.Save();
            // Exit the application.
            Application.Exit();
        }
        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Load all the fixed,removable or a network drive.
        /// </summary>
        ///----------------------------------------------------------------------------------------
        private void LoadDriveInTreeView()
        {
            foreach (DriveInfo di in DriveInfo.GetDrives())
            {
                // Make sure that the drive is readu
                if (di.IsReady && (
                    di.DriveType == DriveType.Fixed ||
                    di.DriveType == DriveType.Network ||
                    di.DriveType == DriveType.Removable
                    ))
                {
                    // Add a new node
                    TreeNode tn = tvFolder.Nodes.Add(di.VolumeLabel + " (" + di.Name + ")");
                    tn.Tag = di.RootDirectory;

                    // For all directories in the root folder, we add a new node in
                    // the TreeView
                    foreach (DirectoryInfo dir in di.RootDirectory.GetDirectories())
                    {
                        TreeNode tnDir = tn.Nodes.Add(dir.Name, dir.Name);
                        tnDir.Tag = dir;
                    }
                }
            }
        }
        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Load all the subfolders of the nodes.
        /// </summary>
        ///----------------------------------------------------------------------------------------
        private void tvFolder_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            // For all the nodes in the nodes that is about to be expand
            foreach (TreeNode node in e.Node.Nodes)
            {
                // Make sure that the tag is a directory info
                if (node.Tag is DirectoryInfo)
                {
                    // Get the DirectoryInfo of the node by the Tag
                    DirectoryInfo di = (DirectoryInfo)node.Tag;

                    // We have to use a Try, because some folders are not accessible and can cause
                    // System error
                    try
                    {
                        // Get the list of directories, this is where it can crash
                        DirectoryInfo[] diList = di.GetDirectories();

                        // For each directory
                        for (int i = 0; i < diList.Count(); i++)
                        {
                            // If the directory is already there, we don't add it
                            if (!node.Nodes.ContainsKey(diList[i].Name))
                            {
                                TreeNode tnDir = node.Nodes.Add(diList[i].Name, diList[i].Name);
                                tnDir.Tag = diList[i];
                            }

                        }
                    }
                    catch (Exception)
                    {

                    }


                }
            }
        }

        #region Extensions
        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Load the extensions into the lvwExt
        /// </summary>
        ///----------------------------------------------------------------------------------------
        private void LoadExtensions()
        {
            // Read the default extension and set a WhiteSmoke background Color
            // TODO: Create the options with user settings for the color
            ReadExtensionsFile(Application.StartupPath + @"\DATA\DefExt.ToolGabData"
                , Color.WhiteSmoke);

            // Read the customized extension file.
            ReadExtensionsFile(Application.StartupPath + @"\DATA\CusExt.ToolGabData");

            // When all extension are load into lvwExt, we make sure that all the column width are 
            // properly sized.
            for (int i = 0; i < lvwExt.Columns.Count; i++)
            {
                lvwExt.Columns[i].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            }
        }

        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Read the extension file and load it into the lvwExt. This will use the default 
        /// background color
        /// </summary>
        /// <param name="FullFilePath">The full extension file path</param>
        ///----------------------------------------------------------------------------------------
        private void ReadExtensionsFile(string FullFilePath)
        {
            ReadExtensionsFile(FullFilePath, SystemColors.ControlLightLight);
        }
        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// Read the extension file and load it into the lvwExt.
        /// </summary>
        /// <param name="FullFilePath">The full extension file path</param>
        /// <param name="BackgroundColor">Background color for this Extension</param>
        ///----------------------------------------------------------------------------------------
        private void ReadExtensionsFile(string FullFilePath, Color BackgroundColor)
        {
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
               new System.IO.StreamReader(FullFilePath);
            while ((line = file.ReadLine()) != null)
            {
                string[] lineSplit;
                lineSplit = line.Split('|');
                if (!lineSplit[0].StartsWith("."))
                    lineSplit[0] = "." + lineSplit[0];
                ListViewItem lvi = new ListViewItem(lineSplit);
                lvi.BackColor = BackgroundColor;
                lvi.Checked = true;
                lvwExt.Items.Add(lvi);
            }

            file.Close();
        }
        #endregion

        private void mainMenuCleanerStart_Click(object sender, EventArgs e)
        {
            CleanerEngine cln = new CleanerEngine();
            cln.CleaningCompleted += new EventHandler(cln_CleaningCompleted);
            cln.CleaningProgressChanged += new CleaningProgressChangedEventHandler(cln_CleaningProgressChanged);
            List<string> diExt = new List<string>();

            foreach (ListViewItem item in lvwExt.Items)
            {
                diExt.Add(item.SubItems[0].Text);
            }


            // Disable the start button
            //btnStart.Enabled = false;
            ssMainProgress.Style = ProgressBarStyle.Marquee;

            // Set the start time
            m_Start = DateTime.Now;
            timElapsed.Start();

            // Empty the items list
            lvwDeletedFiles.Items.Clear();
            m_FilesDeleted = 0;
            cln.Clean(m_chkDI, diExt, true);
            SetInfos();
        }
        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        /// <param name="CleaningProgressChanged"></param>
        ///----------------------------------------------------------------------------------------

        void cln_CleaningProgressChanged(CleaningProgressChangedEventArgs CleaningProgressChanged)
        {
            lvwDeletedFiles.Items.Add(CleaningProgressChanged.IOObject.FullName);
            chDeletedFiles.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            m_FilesDeleted++;
            SetInfos();
        }

        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///----------------------------------------------------------------------------------------
        void cln_CleaningCompleted(object sender, EventArgs e)
        {
            if (sender is CleanerEngine)
            {
                CleanerEngine cln = (CleanerEngine)sender;

                cln.CleaningCompleted -= new EventHandler(cln_CleaningCompleted);
                cln.CleaningProgressChanged -= new CleaningProgressChangedEventHandler(cln_CleaningProgressChanged);
                
                timElapsed.Stop();
                ssMainProgress.Style = ProgressBarStyle.Continuous;
            }
        }
        private void SetInfos()
        {

            ssMainTimeElapsed.Text = (DateTime.Now - m_Start).ToString().Substring(0, 8); ;
            ssMainFilesDeleted.Text = "Files deleted : " + m_FilesDeleted.ToString();
        }

        ///----------------------------------------------------------------------------------------
        /// <summary>
        /// 
        /// </summary>
        ///----------------------------------------------------------------------------------------
        private void tvFolder_AfterCheck(object sender, TreeViewEventArgs e)
        {
            DirectoryInfo di;
            if (e.Node.Tag is DirectoryInfo)
                di = (DirectoryInfo)e.Node.Tag;
            else
                return;

            if (e.Node.Checked)
            {
                if (!m_chkDI.Contains(di))
                    m_chkDI.Add(di);

            }
            else
            {
                if (m_chkDI.Contains(di))
                    m_chkDI.Remove(di);
            }
        }

        private void mainMenuCleanerShortcuts_Click(object sender, EventArgs e)
        {
            ShortcutsForm frmSC = new ShortcutsForm();
            frmSC.ShowDialog();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Make sure we are quitting properly
            ApplicationExit();

        }

        private void mainMenuShowResults_CheckedChanged(object sender, EventArgs e)
        {
           // mainMenuShowResults.Checked = Properties.Settings.Default.ShowResultsWindow;
            tsMainResultView.Checked = mainMenuShowResults.Checked;
            scMain.Panel2Collapsed = !mainMenuShowResults.Checked;
        }

        private void tsMainResultView_Click(object sender, EventArgs e)
        {
            mainMenuShowResults.Checked = tsMainResultView.Checked;
            scMain.Panel2Collapsed = !tsMainResultView.Checked;
        }

        private void timElapsed_Tick(object sender, EventArgs e)
        {
            SetInfos();
        }







    }
}
